package org.hit.burkun.network;

import java.io.Serializable;
import java.util.HashSet;

import org.apache.commons.lang3.StringUtils;
import org.hit.burkun.umls.relation.UniformRelation;

public class EdgeInfo implements Serializable {
	/**
	 * 边序列化
	 */
	private static final long serialVersionUID = 2902424404589437502L;
	private Vertex vertex;
	private double score = -1;
	private HashSet<String> relType = new HashSet<>(); // evidence
	private double orgScore = 1;

	public String getRelType() {
		return StringUtils.join(relType, ",");
	}

	public void setOrgScore(double orgScore) {
		this.orgScore = orgScore;
	}

	public void setRelType(String relTypee) {
		addRelType(relTypee);
	}

	public boolean isInRelType(String type) {
		return relType.contains(type);
	}

	public boolean isInRelType(HashSet<String> types) {
		for (String type : types) {
			if (isInRelType(type)) {
				return true;
			}
		}
		return false;
	}

	public EdgeInfo(Vertex vertex, String relType) {
		this.vertex = vertex;
		addRelType(relType);
	}

	// 不建议使用
	public EdgeInfo(Vertex vertex, double score) {
		this.vertex = vertex;
		this.score = score;
	}

	private void addRelType(String relTypes) {
		String[] rels = relTypes.split(",");
		for (String rel : rels) {
			this.relType.add(rel);
		}
	}

	public Vertex getVertex() {
		return vertex;
	}

	public void setVertex(Vertex vertex) {
		this.vertex = vertex;
	}

	public double getScore() {
		if (score != -1)
			return score;
		// rewrite
		// remove same evidence, 只适用于一个的情况。
		boolean isUsed = false;
		double combineScore = 1.0;
		for (String rel : relType) {
			org.hit.burkun.umls.relation.UniformRelation.TYPE type = UniformRelation.TYPE
					.getTypeByTag(rel);
			if (UniformRelation.containSame(type)) {
				if (!isUsed) {
					combineScore *= (1 - UniformRelation.getScoreByType(type));
					isUsed = true;
				}
			} else {
				combineScore *= (1 - UniformRelation.getScoreByType(type));
			}
		}
		return (1 - combineScore) * UniformRelation.getGlobalWeight(relType)
				* orgScore;
	}

	public void setScore(double score) {
		this.score = score;
	}

	@Override
	public String toString() {
		return this.vertex.toString() + " " + this.getRelType() + " " + score;
	}
}
